package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierDao;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierDao supplierDao;

    @Override
    public void delete(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        supplierDao.delete(list);
    }

    @Override
    public void save(Supplier supplier) {
        Integer id = supplier.getSupplierId();
        if (id == null){
            supplierDao.insert(supplier);
        }else {
            supplierDao.update(supplier);
        }
    }

    @Override
    public Map<String, Object> getSupplierList(Integer page, Integer rows, String supplierName) {
        List<Supplier> supplierList =  supplierDao.selectSupplierList(supplierName);
        Map<String, Object> map = new HashMap<>();
        Integer total =  supplierDao.selectTotal(supplierName);
        int firstIndex = (page - 1) * rows;
        int lastIndex = page * rows;
        if (lastIndex > total){
            lastIndex = total;
        }
        List<Supplier> supplierListPage = supplierList.subList(firstIndex, lastIndex);
        map.put("total",total);
        map.put("rows",supplierListPage);
        return map;
    }
}
